package com.laolang.shop.common.core.util;

import cn.hutool.json.JSONUtil;
import com.laolang.shop.common.core.domain.SimpleAjax;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author khlbat
 * @version 1.0
 * @date 2020/11/1 20:46
 */
public class PrintJsonWriter {

    /**
     * 输出 json 字符串
     *
     * @param response response
     * @param json     需要输出的 json 字符串
     * @throws IOException IOException
     */
    public static void printJson(HttpServletResponse response, String json) throws IOException {
        response.reset();
        //指定返回的格式为JSON格式
        response.setContentType("application/json;charset=utf-8");
        //setContentType与setCharacterEncoding的顺序不能调换，否则还是无法解决中文乱码的问题
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.write(json);
        out.close();
    }

    /**
     * 输出 json 字符串
     *
     * @param response response
     * @param o        需要输出的 对象
     * @throws IOException IOException
     */
    public static void printJson(HttpServletResponse response, Object o) throws IOException {
        response.reset();
        //指定返回的格式为JSON格式
        response.setContentType("application/json;charset=utf-8");
        //setContentType与setCharacterEncoding的顺序不能调换，否则还是无法解决中文乱码的问题
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        String json = JSONUtil.toJsonStr(o);
        out.write(json);
        out.close();
    }

    /**
     * 输出 json 字符串
     *
     * @param response response
     * @param ajax     需要输出的 对象
     * @throws IOException IOException
     */
    public static void printJson(HttpServletResponse response, SimpleAjax<?> ajax) throws IOException {
        response.reset();
        //指定返回的格式为JSON格式
        response.setContentType("application/json;charset=utf-8");
        //setContentType与setCharacterEncoding的顺序不能调换，否则还是无法解决中文乱码的问题
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        String json = JSONUtil.toJsonStr(ajax);
        out.write(json);
        out.close();
    }
}

